package try_codes.p4;

import java.util.Arrays;

public class MyArraylist<E>{
    private Object[] elementData=new Object[][]{};
    private int size;
    private  int DEFAULT_CAPCITY=10;

    public boolean add(E e){
        //1.判断是否需要扩容
        if (size==elementData.length){
            grow();
        }
        elementData[size++]=e;
        return true;
    }

    public E get(int index){
        //判断索引是否越界
        cross(index);
        return (E)elementData[index];

    }
    public E remove(int index){
        cross(index);
        int moveFlad=size-index-1;
        E retrn= (E) elementData[index];
        if (moveFlad!=0) {
            for (; moveFlad > 0; moveFlad--) {
                elementData[index] = elementData[++index];
            }
        }
            elementData[size-1]=null;
        return retrn;
    }
    public void list(){
        for (int i = 0; i <size ; i++) {
            if (elementData[i]!=null) {
                System.out.println(elementData[i]);
            }
        }
    }
    public int size(){
        return size;
    }

    /**
     * 扩容
     */
    private void grow() {
        if (size==0){
            elementData=new Object[DEFAULT_CAPCITY];
        }else {
            elementData= Arrays.copyOf(elementData,elementData.length+elementData.length>>1);
        }
    }
    private void cross(int index){
        if (index>=size || index<0){
            throw  new IndexOutOfBoundsException("索引越界");
        }
    }
}
